package com.future.heatwave.viewmodel

import android.app.Application
import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.future.heatwave.db.VideoDatabase
import com.future.heatwave.db.entity.AchieveDataBean
import com.future.heatwave.db.entity.ObtainRecordsBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class AchieveDataViewModel(application: Application) : AndroidViewModel(application) {
    private val database = VideoDatabase.getDb(application).videoDao()
    private val _items = mutableStateListOf<AchieveDataBean>()
    val items: List<AchieveDataBean> = _items
    suspend fun getAllItems(): List<AchieveDataBean> {
        return database.getAllAchieve()
    }

    fun insertItem(item: AchieveDataBean) {
        viewModelScope.launch {
            // 在 IO 线程执行数据库插入操作
            withContext(Dispatchers.IO) {
                database.insertAchieve(item)
            }
            // 更新 UI 线程的数据
            _items.add(item)
        }
    }

    fun deleteItem(item: AchieveDataBean) {
        viewModelScope.launch {
            // 在 IO 线程执行数据库删除操作
            withContext(Dispatchers.IO) {
                database.deleteAchieve(item)
            }
            // 更新 UI 线程的数据
            _items.remove(item)
        }
    }
}